<template>
  <div class="container p-6">
    <!-- 搜索区域 -->
    <div class="mb-4 flex items-center space-x-4">
      <el-input
        label="班级名称"
        v-model="searchParams.gradeName"
        placeholder="班级"
        class="!w-[200px]"
        clearable
        @input="handleAutoSearch"
        @clear="handleAutoSearch"
        size="large"
      />
      <el-button type="primary" @click="handleAdd" size="large">添加</el-button>
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedRows.length === 0"
        size="large"
        >批量删除</el-button
      >
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        prop="code"
        label="班级编号"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="gradeName"
        label="班级名称"
        min-width="140"
        align="center"
      />
      <el-table-column
        prop="gradeCount"
        label="班级人数"
        min-width="120"
        align="center"
      />

      <el-table-column
        prop="userName"
        label="创建用户"
        min-width="120"
        align="center"
      >
        <template #default="scope">{{
          scope.row?.userName || 'admin'
        }}</template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="120" align="center">
        <template #default="scope">
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="mt-4 flex items-center text-sm text-gray-500">
      <span>共 {{ searchParams.total }} 条</span>
      <div class="ml-4 flex items-center">
        <el-select
          v-model="searchParams.pageSize"
          class="!w-[100px] mr-2"
          @change="handleSizeChange"
        >
          <el-option
            v-for="size in [10, 20, 30, 50]"
            :key="size"
            :label="`${size}条/页`"
            :value="size"
          />
        </el-select>
        <el-pagination
          v-model:current-page="searchParams.pageNum"
          :page-size="searchParams.pageSize"
          layout="prev, pager, next"
          :total="searchParams.total"
          :pager-count="5"
          background
          @current-change="handleCurrentChange"
        />
        <span class="mx-2">前往</span>
        <el-input
          v-model="jumpPage"
          class="!w-[50px]"
          @keyup.enter="handleJumpPage"
        />
        <span class="mx-2">页</span>
      </div>
    </div>

    <!-- 添加学生侧边栏 -->
    <el-drawer
      v-model="dialogVisible"
      :title="isEditMode ? '编辑班级' : '添加班级'"
      :modal="true"
      size="350px"
      :close-on-click-modal="false"
      direction="rtl"
      destroy-on-close
    >
      <template #default>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="drawer-form"
        >
          <el-form-item label="班级名称" prop="gradeName">
            <el-input v-model="form.gradeName" placeholder="班级名称" />
          </el-form-item>
          <el-form-item label="班级编号" prop="code">
            <el-input v-model="form.code" placeholder="班级编号" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import {
  getGradelist,
  addGrade,
  deleteGrade,
  editGrade,
  batchDeleteGrade,
} from '@/api/teacher/classmanage'

// 防抖定时器
let searchTimer = null

// 表格数据
const tableData = ref([])

// 分页相关
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 10,
  gradeName: '',
  gradeId: '',
})

// 选中的行
const selectedRows = ref([])

// 弹窗显示控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditId = ref('')
// 表单ref
const formRef = ref()

// 表单数据
const form = reactive({
  gradeName: '',
  code: '',
})

// 表单验证规则
const rules = {
  gradeName: [{ required: true, message: '请输入班级名称', trigger: 'blur' }],
  // code只能是数字
  code: [
    { required: true, message: '请输入班级编号', trigger: 'blur' },
    { pattern: /^\d+$/, message: '班级编号只能是数字', trigger: 'blur' }
  ],
}

// 获取班级列表
const getGradeList = async () => {
  const {
    data: { records, total, current, size },
  } = await getGradelist(searchParams)
  tableData.value = records
  searchParams.total = total
  searchParams.pageNum = current
  searchParams.pageSize = size
}

// 处理搜索
const handleSearch = () => {
  getGradeList()
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该班级吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, msg } = await deleteGrade(row.id)
      if (code == 0) {
        ElMessage.error('删除失败' + msg)
        return
      }
      getGradeList()
      ElMessage.success('删除成功')
    })
    .catch(() => {
      // 取消删除
    })
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  searchParams.pageSize = val
  // TODO: 重新加载数据
}

// 处理页码变化
const handleCurrentChange = (val) => {
  searchParams.pageNum = val
  // TODO: 重新加载数据
  getGradeList()
}

// 处理跳转页码
const jumpPage = ref('')
const handleJumpPage = () => {
  // TODO: 实现跳转逻辑
  searchParams.pageNum = Number(jumpPage.value)
  getGradeList()
}

// 打开添加弹窗
const handleAdd = () => {
  isEditMode.value = false
  dialogVisible.value = true
  form.gradeName = ''
  form.code = ''
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, row)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 这里添加提交到后端的逻辑
      const newGrade = {
        ...form,
      }
      const { code, data, msg } = isEditMode.value
        ? await editGrade({ newGrade, id: currentEditId.value })
        : await addGrade(newGrade)
      if (code == 0) {
        ElMessage.error('添加失败' + msg)
        return
      }

      ElMessage.success('添加成功')
      dialogVisible.value = false
      // 刷新表格数据
      getGradeList()
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 自动搜索处理函数（添加防抖）
const handleAutoSearch = () => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }

  // 设置新的定时器，延迟300ms执行搜索
  searchTimer = setTimeout(() => {
    getGradeList()
  }, 300)
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个班级吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        // 获取所有选中行的ID
        const ids = selectedRows.value.map((row) => row.id)

        // 调用批量删除API
        const { code, msg } = await batchDeleteGrade(ids)

        if (code == 0) {
          ElMessage.error('批量删除失败：' + msg)
          return
        }

        ElMessage.success('批量删除成功')
        // 刷新表格数据
        getGradeList()
        // 清空选中
        selectedRows.value = []
      } catch (error) {
        console.error('批量删除出错：', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消删除
    })
}

// 挂载
onMounted(() => {
  // 获取班级信息
  getGradeList()
})
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

:deep(.el-table) {
  .cell {
    display: flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
  }

  .el-table__header th {
    .cell {
      justify-content: center;
    }
  }

  .el-button {
    margin: 0 auto;
  }
}

// 上传区域样式
:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 2px dashed #e6e6e6;
  border-radius: 8px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon--upload {
    font-size: 48px;
    color: #909399;
    margin-bottom: 12px;
  }

  .upload-text {
    color: #606266;
    font-size: 14px;
    text-align: center;

    .text-primary {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
}

// 分页样式
:deep(.el-pagination) {
  .el-pagination__total {
    margin-right: 16px;
  }

  .el-pagination__sizes {
    margin-right: 16px;
  }

  .el-pager li {
    background-color: transparent;

    &.is-active {
      background-color: var(--el-color-primary);
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    background-color: transparent;
  }

  .el-input__inner {
    text-align: center;
    padding: 0 5px;
  }
}

// 下拉选择框样式
:deep(.el-select) {
  .el-input__wrapper {
    background-color: transparent;
  }
}

:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;
  }
}

// 抽屉表单样式
:deep(.el-drawer__body) {
  padding: 20px;

  .drawer-form {
    height: calc(100% - 60px);
    overflow-y: auto;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: white;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
